package com.kcsj.dao;

import com.kcsj.domain.MarkDown;
import com.kcsj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
public class MarkDownDao {
    public static MarkDownDao markDownDao = new MarkDownDao();
    public static MarkDownDao getInstance() {return markDownDao;}

    public MarkDown find(Integer userId,Connection conn) throws SQLException {
        //预编译方式进行查询
        MarkDown markDown = null;
        String s = "select * from MarkDown where user_id = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(s);
        preparedStatement.setInt(1,userId);
        ResultSet resultSet = preparedStatement.executeQuery();
        //将查询到的数据存到departments集合中
        while (resultSet.next()){
            int user_id = resultSet.getInt(1);
            String content = resultSet.getString(2);
            markDown = new MarkDown(user_id,content);
        }
        JdbcHelper.close(resultSet,preparedStatement);
        return markDown;
    }
    
    public boolean add(MarkDown markDown, Connection conn) throws SQLException {
        //使用预编译创建SQL语句
        this.delete(markDown.getUser_id(),conn);
        String sql = "insert into MarkDown(content,user_id)" +
                " values (?,?)";
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1,markDown.getContent());
        statement.setInt(2,markDown.getUser_id());
        int rowsAffected = statement.executeUpdate();
        //执行SQL语句并返回结果和关闭连接
        return rowsAffected > 0;
    }

    //在school表根据id删除相应数据
    public boolean delete(Integer id, Connection conn) throws SQLException {
        //预编译方式进行删除数据
        String s = "delete from MarkDown where user_id = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(s);
        preparedStatement.setInt(1,id);
        //如果执行影响行数大于0，则增加成功
        int i = preparedStatement.executeUpdate();
        //关闭连接
        JdbcHelper.close(preparedStatement);
        return i > 0;
    }
}
